package com.leo.erp.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leo.erp.dao.DepotHeadDao;
import com.leo.erp.dao.DepotHeadMapper;
import com.leo.erp.dto.DepotHeadExecution;
import com.leo.erp.entity.DepotHeadVo4List;
import com.leo.erp.enums.DepotHeadStateEnum;
import com.leo.erp.service.DepotHeadService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.PageCalculator;
import com.leo.erp.util.Tools;

@Service
public class DepotHeadServiceImpl implements DepotHeadService{
	@Autowired
	private DepotHeadMapper depotHeadMapper;
	@Autowired
	private DepotHeadDao depotHeadDao;

	@Override
	public BigDecimal getBuyAndSaleStatistics(String type, String subType, int hasSupplier, String beginTime,
			String endTime) {
		return depotHeadDao.getBuyAndSaleStatistics(type, subType, hasSupplier, beginTime, endTime);
	}

	@Override
	public BigDecimal getBuyAndSaleRetailStatistics(String type, String subType, int hasSupplier, String beginTime,
			String endTime) {
		return depotHeadDao.getBuyAndSaleRetailStatistics(type, subType, hasSupplier, beginTime, endTime);
	}

	@Override
	public DepotHeadExecution list(String type, String subType, String number, String beginTime, String endTime,
			String materialParam, String depotIds, int offset, int rows) {
		DepotHeadExecution de = new DepotHeadExecution();
		List<DepotHeadVo4List> resList = new ArrayList<>();
		List<DepotHeadVo4List> list = null;
		try {
			//页码转换数据库的行码
			int rowIndex = PageCalculator.calculateRowIndex(offset, rows);
			list = depotHeadDao.selectByConditionDepotHead(type, subType, number, beginTime, endTime, materialParam, depotIds, rowIndex, rows);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		if(null != list) {
			for(DepotHeadVo4List dh : list) {
				if(dh.getAccountIdList() != null) {
					String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
					dh.setAccountIdList(accountidlistStr);
				}
				if(dh.getAccountMoneyList() != null) {
                    String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setAccountMoneyList(accountmoneylistStr);
                }
                if(dh.getOtherMoneyList() != null) {
                    String otherMoneyListStr = dh.getOtherMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                    dh.setOtherMoneyList(otherMoneyListStr);
                }
                if(dh.getChangeAmount() != 0) {
                    dh.setChangeAmount(dh.getChangeAmount());
                }
                if(dh.getTotalPrice() != 0) {
                    dh.setTotalPrice(dh.getTotalPrice());
                }
                if(dh.getOperTime() != null) {
                    dh.setOpertimeStr(Tools.getCenternTime(dh.getOperTime()));
                }
                dh.setMaterialsList(findMaterialsListByHeaderId(dh.getDepotHeadId()));
                resList.add(dh);
                de.setState(DepotHeadStateEnum.SUCCESS.getState());
                de.setDepotHeadVo4List(resList);
			}
		}else {
			de.setState(DepotHeadStateEnum.OFFLINE.getState());
		}
		return de;
	}

	private String findMaterialsListByHeaderId(int depotHeadId) {
		String result = null;
        try{
            result = depotHeadDao.findMaterialsListByHeaderId(depotHeadId);
        }catch(GlobalRuntimeException e){
            e.printStackTrace();
        }
        return result;
	}
	
	/**
     * 查询单位的累计应收和累计应付，零售不能计入
     * @param supplierId
     * @param endTime
     * @param supType
     * @return
     */
	@Override
	public DepotHeadExecution findTotalPay(int supplierId, String endTime, String supType) {
		DepotHeadExecution de = new DepotHeadExecution();
		Double sum = 0.0;
		int i = 1;
		if (("customer").equals(supType)) { //客户
            i = 1;
        } else if (("vendor").equals(supType)) { //供应商
            i = -1;
        }
        //进销部分
		sum = sum - ((allMoney(supplierId, "入库", "采购", "合计",endTime) - allMoney(supplierId, "入库", "采购", "实际",endTime)) * (i));
        sum = sum - ((allMoney(supplierId, "入库", "销售退货", "合计",endTime) - allMoney(supplierId, "入库", "销售退货", "实际",endTime)) * (i));
        sum = sum + ((allMoney(supplierId, "出库", "销售", "合计",endTime) - allMoney(supplierId, "出库", "销售", "实际",endTime)) * (i));
        sum = sum + ((allMoney(supplierId, "出库", "采购退货", "合计",endTime) - allMoney(supplierId, "出库", "采购退货", "实际",endTime)) * (i));
		
        de.setTotalPay(sum);
        
		return de;
	}

	 /**
     * 统计总金额
     * @param gets
     * @param type
     * @param subType
     * @param mode 合计或者金额
     * @return
     */
	private Double allMoney(int supplierId, String type, String subType, String mode, String endTime) {
		Double allMoney = null;
		try {
			Double sum = findAllMoney(supplierId, type, subType, mode, endTime);
			if(sum != null) {
				allMoney = sum;
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		if(allMoney == null) {
			allMoney = 0.0;
		}
		//返回正数，如果负数也转为正数
        allMoney = Math.abs(allMoney);
		
		return allMoney;
	}

	private Double findAllMoney(int supplierId, String type, String subType, String mode, String endTime) {
		String modeName = "";
		Double allOtherMoney = 0.0;
		if (mode.equals("实际")) {
            modeName = "changeAmount";
        } else if (mode.equals("合计")) {
            modeName = "discountLastMoney";
            allOtherMoney = depotHeadDao.findAllOtherMoney(supplierId, type, subType, endTime);
        }
		
		Double result = 0.0;
		try {
			result = depotHeadDao.findAllMoney(supplierId, type, subType, modeName, endTime);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		if(allOtherMoney != null) {
            result = result + allOtherMoney;
        }
		return result;
	}
	
}
